package com.tj.collection.controller.report;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Maps;
import com.kly.user.dto.chatter.ChatterDto;
import com.kly.user.dto.report.*;
import com.kly.user.service.ChatterService;
import com.kly.user.service.ReportQueryService;
import com.tj.collection.bean.ApiResponse;
import com.tj.collection.common.Result;
import com.tj.collection.controller.BaseCompent;
import com.tj.collection.controller.report.request.*;
import com.tj.collection.controller.report.response.*;
import com.tj.collection.db.dao.RewardLevelInfoDao;
import com.tj.collection.db.entity.RewardLevelInfoEntity;
import com.tj.collection.db.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/report")
@Api(value = "报表相关接口", tags = {"报表相关接口"})
public class ReportController extends BaseCompent {

    @Resource
    ReportQueryService reportQueryService;
    @Resource
    ChatterService chatterService;
    @Resource
    RewardLevelInfoDao rewardLevelInfoDao;
    @NacosValue(value = "${chatter.url}", autoRefreshed = true)
    private String chatterApiUrl;
    @Resource
    AdminService adminService;

    @ApiOperation("在线率总表接口")
    @RequestMapping(value = "/onlineTotalReport", method = {RequestMethod.POST})
    public ApiResponse onlineTotalReport(@RequestBody OnlineReportReq request) {

        final BaseCompent.AccountRole accountRole = getAccountRole();

        final OnlineReportRequest onlineReportRequest = OnlineReportRequest.builder().startDate(toBeginDate(request.getStartDate())).endDate(toEndDate(request.getEndDate())).account(request.getChatterAccount()).nickName(request.getChatterNickName()).build();
        if (!accountRole.getHasViewAllDataPermission()) {
            onlineReportRequest.setChatterCodes(accountRole.getChatterCodes());
        }

        final OnlineReportResp onlineReport = reportQueryService.getOnlineTotalReport(onlineReportRequest, new Page(request.getPageSize(), request.getCurrent()));
        final List<OnlineReportDto> onlineReportDtoList = onlineReport.getOnlineReportDtoList();
        OnlineReportResponse onlineReportResponse = OnlineReportResponse.builder().totalNum(onlineReport.getTotalNum()).onlineAvgRage(onlineReport.getOnlineAvgRage()).workingTimeOnlineRage(onlineReport.getWorkingTimeOnlineRage()).build();
        if (CollectionUtils.isNotEmpty(onlineReportDtoList)) {
            final List<OnlineReportDto> onlineReportDtos = onlineReportDtoList.stream().map(o -> {
                o.setWorkingTimeOnlineRage(o.getWorkingTimeOnlineRage());
                o.setQueryTime("20" + o.getQueryDate());
                return o;
            }).collect(Collectors.toList());
            onlineReportResponse.setOnlineReportDtoList(onlineReportDtos);
        }
        return new ApiResponse(onlineReportResponse);


    }


    @ApiOperation("在线率报表接口")
    @RequestMapping(value = "/onlineReport", method = {RequestMethod.POST})
    public ApiResponse onlineReport(@RequestBody OnlineReportReq request) {

        final OnlineReportRequest onlineReportRequest = OnlineReportRequest.builder().startDate(toBeginDate(request.getStartDate())).endDate(toEndDate(request.getEndDate())).account(request.getChatterAccount()).nickName(request.getChatterNickName()).build();

        final OnlineReportResp onlineReport = reportQueryService.getOnlineReport(onlineReportRequest, new Page(request.getPageSize(), request.getCurrent()));

        final List<OnlineReportDto> onlineReportDtoList = onlineReport.getOnlineReportDtoList();
        OnlineReportResponse onlineReportResponse = OnlineReportResponse.builder().totalNum(onlineReport.getTotalNum()).onlineAvgRage(onlineReport.getOnlineAvgRage()).workingTimeOnlineRage(onlineReport.getWorkingTimeOnlineRage()).build();
        if (CollectionUtils.isNotEmpty(onlineReportDtoList)) {
            final List<OnlineReportDto> onlineReportDtos = onlineReportDtoList.stream().map(o -> {
                o.setQueryTime(o.getQueryTime() + "-" + (Integer.parseInt(o.getQueryTime()) + 1));
                return o;
            }).collect(Collectors.toList());
            onlineReportResponse.setOnlineReportDtoList(onlineReportDtos);
        }
        return new ApiResponse(onlineReportResponse);


    }

    @ApiOperation("回复率报表接口")
    @RequestMapping(value = "/messageReport", method = {RequestMethod.POST})
    public ApiResponse messageReport(@RequestBody MessageReportRequest request) {

        final ReplyReportRequest replyReportRequest = ReplyReportRequest.builder().account(request.getChatterAccount()).nickName(request.getChatterNickName()).startDate(toBeginDate(request.getStartDate())).endDate(toEndDate(request.getEndDate())).build();
        final ReplyReportResp replyReports = reportQueryService.getReplyReport(replyReportRequest, new Page(request.getPageSize(), request.getCurrent()));

        final ReplyReportResponse replyReportResponse = ReplyReportResponse.builder().build();
        BeanUtils.copyProperties(replyReports, replyReportResponse);

        return new ApiResponse(replyReportResponse);
    }

    @ApiOperation("回复率总表接口")
    @RequestMapping(value = "/messageReportTotal", method = {RequestMethod.POST})
    public ApiResponse messageReportTotal(@RequestBody MessageReportRequest request) {
        final BaseCompent.AccountRole accountRole = getAccountRole();

        final ReplyReportRequest replyReportRequest = ReplyReportRequest.builder().account(request.getChatterAccount()).nickName(request.getChatterNickName()).startDate(toBeginDate(request.getStartDate())).endDate(toEndDate(request.getEndDate())).build();
        if (!accountRole.getHasViewAllDataPermission()) {
            replyReportRequest.setChatterCodes(accountRole.getChatterCodes());
        }
        final ReplyReportResp replyReports = reportQueryService.getReplyReportTotal(replyReportRequest, new Page(request.getPageSize(), request.getCurrent()));

        final ReplyReportResponse replyReportResponse = ReplyReportResponse.builder().build();
        BeanUtils.copyProperties(replyReports, replyReportResponse);

        return new ApiResponse(replyReportResponse);
    }

    @RequestMapping(value = "/reward/level", method = {RequestMethod.POST})
    public ApiResponse ratingLevel(@RequestBody RatingLevelRequest request) {

        List<ChatterDto> chatterUserCodes = chatterService.getChatterUserCode(request.getChatterAccount(), request.getChatterNickName());;
        if (CollectionUtils.isEmpty(chatterUserCodes)) {
            return new ApiResponse(RewardReportResponse.builder().build());
        }

        final List<String> chatters = chatterUserCodes.stream().map(ChatterDto::getChatterCode).collect(Collectors.toList());

        final int rewardLevelInfoCnt = rewardLevelInfoDao.getRewardLevelInfoCnt(chatters, toBeginDate(request.getStartDate()), toEndDate(request.getEndDate()), new Page(request.getPageSize(), request.getCurrent()));
        if (rewardLevelInfoCnt == 0) {
            return new ApiResponse(RewardReportResponse.builder().build());
        }

        final List<RewardLevelInfoEntity> rewardLevelInfoEntities = rewardLevelInfoDao.listRewardLevelInfo(chatters, toBeginDate(request.getStartDate()), toEndDate(request.getEndDate()), new Page(request.getPageSize(), request.getCurrent()));

        final HashMap<String, ChatterDto> groupByChatters = Maps.newHashMap();
        for (ChatterDto dto : chatterUserCodes) {
            groupByChatters.put(dto.getChatterCode(), dto);
        }

        final List<RewardLevelInfoDto> rewardLevelInfoDtoList = rewardLevelInfoEntities.stream().map(o -> RewardLevelInfoDto.builder().chatterAccount(groupByChatters.get(o.getUserCode()).getAccount()).chatterNickName(groupByChatters.get(o.getUserCode()).getNickName())
                .chatterUserCode(o.getUserCode()).rewardLevel(o.getLevel()).build()).collect(Collectors.toList());

        return new ApiResponse(RewardReportResponse.builder().rewardReportDtoList(rewardLevelInfoDtoList).totalNum(rewardLevelInfoCnt).build());
    }

    @RequestMapping(value = "/chatter/reward/list", method = {RequestMethod.POST})
    public ApiResponse rewardList(@RequestBody ChatterRewardReportReq request) {
        final BaseCompent.AccountRole accountRole = getAccountRole();

        setupQueryParams(request, accountRole);

        Map<String, String> header = Maps.newHashMap();
        header.put("Content-Type", "application/json");

        final String response = HttpUtil.postPageBody(chatterApiUrl + "/api/chat/reward/list", header, JSONObject.toJSONString(request));

        if (StringUtils.isEmpty(response)) {
            return new ApiResponse();
        }
        final JSONObject responseJson = JSONObject.parseObject(response);
        if (responseJson.getIntValue("code") != 0) {
            return new ApiResponse();
        }

        final String data = responseJson.getString("data");
        if (StringUtils.isEmpty(data)) {
            return new ApiResponse();
        }

        final ChatterRewardResp chatterRewardResp = JSONObject.parseObject(data, ChatterRewardResp.class);

        return new ApiResponse(chatterRewardResp);
    }

    @RequestMapping(value = "/chatter/chats/payments/list", method = {RequestMethod.POST})
    @ApiOperation("Chatter Session & Payment 列表")
    public Result<ChatPaymentsListResp> chatPaymentList(@RequestBody ChatterChatPaymentsReq request) {
        return Result.ok(ChatPaymentsListResp.builder().build());
    }

    private ChatterRewardReportReq setupQueryParams(@RequestBody ChatterRewardReportReq request, BaseCompent.AccountRole accountRole) {
        request.setStartDate(convertBeginDate(request.getStartDate()));
        request.setEndDate(convertEndDate(request.getEndDate()));
        if (!accountRole.getHasViewAllDataPermission()) {
            request.setChatterCodes(accountRole.getChatterCodes());
        }
        return request;
    }
}
